package search.kspatial.cn.service;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import search.kspatial.cn.dao.IElementDao;
import search.kspatial.cn.dao.IUserDao;
import search.kspatial.cn.pojo.User;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author KK
 * @create 2021/11/16 23:37
 */
public class UserService {
    private InputStream in;
    private SqlSession session;
    private IUserDao iUserDao;

    /**
     * 初始化
     *
     * @throws IOException
     */
    public void init() throws IOException {
        //1.获取配置文件
        in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //2.获取SqlSessionFactory
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        //3.获取SqlSession对象
        session = factory.openSession();
        //4.获取代理对象
        iUserDao = session.getMapper(IUserDao.class);
    }

    /**
     * 事务提交并释放资源
     *
     * @throws IOException
     */
    public void destroy() throws IOException {
        //1.提交事务
        session.commit();
        //2.释放资源
        session.close();
        in.close();
    }

    /**
     * 登录
     * @param user
     * @return
     * @throws IOException
     */
    public User login(User user) throws IOException {
        init();
        return iUserDao.loginU(user);
    }
}
